package com.main.back;

import com.main.bean.*;
import com.main.utils.SqlHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import static com.main.utils.ConstUtil.*;

@WebServlet(name="index",urlPatterns="/index")
public class Index extends HttpServlet {
    /**
     * 处理浏览器GET请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }

    /**
     * 处理浏览器POST请求
     * @param req
     * @param resp
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //调整编码，防止中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //获取请求来自于哪里，做什么动作
        String action = req.getParameter("action");
        //回调结果
        PrintWriter printWriter = resp.getWriter();
        //判断动作
        if (action != null) {
            switch (action) {
                case ACTION_LOGIN:
                    printWriter.print(doLogin(req));
                    break;
                case ACTION_SIGN:
                    printWriter.print(doSign(req));
                    break;
                case ACTION_GET_ATTRACTIONS:
                    printWriter.print(doGetAttractions(req));
                    break;
                case ACTION_ADD_ATTRACTIONS:
                    printWriter.print(doAddAttractions(req));
                    break;
                case ACTION_UPDATE_ATTRACTIONS:
                    printWriter.print(doUpdateAttractions(req));
                    break;
                case ACTION_DEL_ATTRACTIONS:
                    printWriter.print(doDelAttractions(req));
                    break;
                case ACTION_GET_TICKETS:
                    printWriter.print(doGetTicket(req));
                    break;
                case ACTION_ADD_TICKETS:
                    printWriter.print(doAddTicket(req));
                    break;
                case ACTION_UPDATE_TICKETS:
                    printWriter.print(doUpdateTicket(req));
                    break;
                case ACTION_DEL_TICKETS:
                    printWriter.print(doDelTicket(req));
                    break;
                case ACTION_GET_USERS:
                    printWriter.print(doGelUsers(req));
                    break;
                case ACTION_UPDATE_USER_PWD:
                    printWriter.print(doUpdateUserPwd(req));
                    break;
                case ACTION_GET_USER_ORDER:
                    printWriter.print(doGetUserOrder(req));
                    break;
                case ACTION_GET_ADMIN_ORDER:
                    printWriter.print(doGetAdminOrder(req));
                    break;
                case ACTION_ADD_ORDER:
                    printWriter.print(doAddOrder(req));
                    break;
                case ACTION_DEL_ORDER:
                    printWriter.print(doDelOrder(req));
                    break;
                case ACTION_GET_SALES:
                    printWriter.print(doGetSales(req));
                    break;
                case ACTION_GET_USER_INFO:
                    printWriter.print(doGetUserInfo(req));
                    break;
                case ACTION_SET_USER_INFO:
                    printWriter.print(doSetUserInfo(req));
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 登录
     * @param req
     * @return
     */
    private String doLogin(HttpServletRequest req) {
        String sql = "select * from users where phone=? and pwd=?";
        String[] p = {
                req.getParameter("phone"),
                req.getParameter("pwd")
        };
        UserBean userBean = SqlHelper.doObjQuery(sql, p, UserBean.class);
        if (userBean != null) {
            JSONObject jsonObject = JSONObject.fromObject(userBean);
            return jsonObject.toString();
        } else {
            return "";
        }
    }

    /**
     * 注册
     * @param req
     * @return
     */
    private Boolean doSign(HttpServletRequest req) {
        String sql = "insert into users(phone,pwd) select ?,? from dual where not exists (select id from users where phone=?)";
        String[] p = {
                req.getParameter("phone"),
                req.getParameter("pwd"),
                req.getParameter("phone")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result > 0;
    }

    /**
     * 获取全部景点
     * @param req
     * @return
     */
    private String doGetAttractions(HttpServletRequest req) {
        String sql = "select * from attractions order by id desc";
        List<AttractionsBean> attractionsBeanList = SqlHelper.doListQuery(sql, null, AttractionsBean.class);
        if (attractionsBeanList != null) {
            JSONArray jsonArray = JSONArray.fromObject(attractionsBeanList);
            return jsonArray.toString();
        } else {
            return "";
        }
    }

    /**
     * 添加景点
     * @param req
     * @return
     */
    private boolean doAddAttractions(HttpServletRequest req) {
        String sql = "insert into attractions(name, description, address, level) values(?,?,?,?)";
        String[] p = {
                req.getParameter("name"),
                req.getParameter("description"),
                req.getParameter("address"),
                req.getParameter("level")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result>0;
    }

    /**
     * 更新景点
     * @param req
     * @return
     */
    private boolean doUpdateAttractions(HttpServletRequest req) {
        String sql = "update attractions set name=?,description=?,address=?,level=? where id=?";
        String[] p = {
                req.getParameter("name"),
                req.getParameter("description"),
                req.getParameter("address"),
                req.getParameter("level"),
                req.getParameter("id")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result>0;
    }

    /**
     * 删除景点
     * @param req
     * @return
     */
    private boolean doDelAttractions(HttpServletRequest req) {
        String sql = "delete from attractions where id=?";
        String[] p = {
                req.getParameter("id")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result>0;
    }

    /**
     * 获取指定景点的门票
     * @param req
     * @return
     */
    private String doGetTicket(HttpServletRequest req) {
        String sql = "select * from tickets where attractions_id=?";
        String[] p = {
                req.getParameter("attractions_id")
        };
        List<TicketBean> ticketBeanList = SqlHelper.doListQuery(sql, p, TicketBean.class);
        if (ticketBeanList != null) {
            JSONArray jsonArray = JSONArray.fromObject(ticketBeanList);
            return jsonArray.toString();
        } else {
            return "";
        }
    }

    /**
     * 添加景点门票
     * @param req
     * @return
     */
    private boolean doAddTicket(HttpServletRequest req) {
        String sql = "insert into tickets(attractions_id, sort, price, count) values(?,?,?,?)";
        String[] p = {
                req.getParameter("attractions_id"),
                req.getParameter("sort"),
                req.getParameter("price"),
                req.getParameter("count")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result>0;
    }

    /**
     * 更新景点门票
     * @param req
     * @return
     */
    private boolean doUpdateTicket(HttpServletRequest req) {
        String sql = "update tickets set sort=?,price=?,count=? where id=?";
        String[] p = {
                req.getParameter("sort"),
                req.getParameter("price"),
                req.getParameter("count"),
                req.getParameter("id")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result>0;
    }

    /**
     * 删除景点门票
     * @param req
     * @return
     */
    private boolean doDelTicket(HttpServletRequest req) {
        String sql = "delete from tickets where id=?";
        String[] p = {
                req.getParameter("id")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result>0;
    }

    /**
     * 获取用户
     * @param req
     * @return
     */
    private String doGelUsers(HttpServletRequest req) {
        String sql = "select * from users where phone != 'admin' order by id desc";
        List<UserBean> userBeanList = SqlHelper.doListQuery(sql, null, UserBean.class);
        if (userBeanList != null) {
            JSONArray jsonArray = JSONArray.fromObject(userBeanList);
            return jsonArray.toString();
        } else {
            return "";
        }
    }

    /**
     * 修改用户密码
     * @param req
     * @return
     */
    private boolean doUpdateUserPwd(HttpServletRequest req) {
        String sql = "update users set pwd=? where id=?";
        String[] p = {
                req.getParameter("pwd"),
                req.getParameter("id")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result>0;
    }

    /**
     * 用户获取订单
     * @param req
     * @return
     */
    private String doGetUserOrder(HttpServletRequest req) {
        String sql = "select orders.*,attractions.name,tickets.sort,tickets.price from orders,tickets,attractions where orders.user_id=? and orders.ticket_id=tickets.id and tickets.attractions_id=attractions.id order by id desc";
        String[] p = {
                req.getParameter("user_id")
        };
        List<OrderBean> orderBeanList = SqlHelper.doListQuery(sql, p, OrderBean.class);
        if (orderBeanList != null) {
            JSONArray jsonArray = JSONArray.fromObject(orderBeanList);
            return jsonArray.toString();
        } else {
            return "";
        }
    }


    /**
     * 管理员获取订单
     * @param req
     * @return
     */
    private String doGetAdminOrder(HttpServletRequest req) {
        String sql = "select orders.*,attractions.name,tickets.sort,tickets.price from orders,tickets,attractions where orders.ticket_id=tickets.id and tickets.attractions_id=attractions.id order by id desc";
        List<OrderBean> orderBeanList = SqlHelper.doListQuery(sql, null, OrderBean.class);
        if (orderBeanList != null) {
            JSONArray jsonArray = JSONArray.fromObject(orderBeanList);
            return jsonArray.toString();
        } else {
            return "";
        }
    }

    /**
     * 添加订单
     * @param req
     * @return
     */
    private boolean doAddOrder(HttpServletRequest req) {
        String sql_check = "update tickets set count=count-1 where id=?";
        String[] p_check = {
                req.getParameter("ticket_id")
        };
        SqlHelper.doUpdate(sql_check, p_check);
        String sql = "insert into orders(user_id, ticket_id, time) values(?,?,?)";
        String[] p = {
                req.getParameter("user_id"),
                req.getParameter("ticket_id"),
                req.getParameter("time")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result>0;
    }

    /**
     * 取消订单
     * @param req
     * @return
     */
    private boolean doDelOrder(HttpServletRequest req) {
        String sql_check = "update tickets set count=count+1 where id=?";
        String[] p_check = {
                req.getParameter("ticket_id")
        };
        SqlHelper.doUpdate(sql_check, p_check);
        String sql = "delete from orders where id=?";
        String[] p = {
                req.getParameter("id")
        };
        int result = SqlHelper.doUpdate(sql, p);
        return result>0;
    }

    /**
     * 获取销量
     * @param req
     * @return
     */
    private String doGetSales(HttpServletRequest req) {
        String sql = "select orders.*,attractions.name,tickets.sort,tickets.price from orders,tickets,attractions where attractions.id=? and orders.ticket_id=tickets.id and tickets.attractions_id=attractions.id order by id desc";
        String[] p = {
                req.getParameter("attractions_id")
        };
        List<OrderBean> orderBeanList = SqlHelper.doListQuery(sql, p, OrderBean.class);
        if (orderBeanList != null) {
            JSONArray jsonArray = JSONArray.fromObject(orderBeanList);
            return jsonArray.toString();
        } else {
            return "";
        }
    }

    /**
     * 获取用户信息
     * @param req
     * @return
     */
    private String doGetUserInfo(HttpServletRequest req) {
        String sql = "select * from userinfo where user_id=?";
        String[] p = {
                req.getParameter("user_id")
        };
        UserInfoBean userInfoBean = SqlHelper.doObjQuery(sql, p, UserInfoBean.class);
        if (userInfoBean != null) {
            JSONObject jsonObject = JSONObject.fromObject(userInfoBean);
            return jsonObject.toString();
        } else {
            return "";
        }
    }

    /**
     * 设置用户信息
     * @param req
     * @return
     */
    private boolean doSetUserInfo(HttpServletRequest req) {
        String test = doGetUserInfo(req);
        if (test == null || test.equals("")) {
            String sql = "insert into userinfo(user_id,name,sex,age,address) values(?,?,?,?,?)";
            String[] p = {
                    req.getParameter("user_id"),
                    req.getParameter("name"),
                    req.getParameter("sex"),
                    req.getParameter("age"),
                    req.getParameter("address")
            };
            int result = SqlHelper.doUpdate(sql, p);
            return result>0;
        } else {
            String sql = "update userinfo set name=?,sex=?,age=?,address=? where user_id=?";
            String[] p = {
                    req.getParameter("name"),
                    req.getParameter("sex"),
                    req.getParameter("age"),
                    req.getParameter("address"),
                    req.getParameter("user_id")
            };
            int result = SqlHelper.doUpdate(sql, p);
            return result>0;
        }
    }
}
